/**
 * Copyright © 2021-2025 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.wutu.nbyjk8.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.excel.util.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wutu.nbyjk8.domain.DataSourceManage;
import com.wutu.nbyjk8.mapper.DataSourceManageMapper;
import com.wutu.nbyjk8.utils.GeoStrGeneratorUtils;
import com.wutu.nbyjk8.vo.QueryVO;
import com.wutu.nbyjk8.vo.ResVO;
import com.wutu.nbyjk8.vo.SaveVO;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 数据源管理Service
 *
 * @author 朱欢乐
 * @version 2023-06-19
 */
@Service
@Transactional
public class DataSourceManageService extends ServiceImpl<DataSourceManageMapper, DataSourceManage> {


    @Autowired
    DataSourceManageMapper dataSourceManageMapper;

    public ResVO selectByType(QueryVO queryVO) {
        Map<String, Object> geoMap = queryVO.getGeometry();
        if (geoMap != null && geoMap.get("type") != null) {
            String geoType = null == geoMap ? "" : String.valueOf(geoMap.get("type"));
            Object geoParam = null == geoMap ? null : geoMap.get("coordinates");
            String itemStr = GeoStrGeneratorUtils.getStr(geoType, geoParam);
            queryVO.setGeoStr(itemStr);
            queryVO.setType(String.valueOf(geoMap.get("type")));
            queryVO.setCoordinates(geoMap.get("coordinates").toString());
        }
        queryVO.setTbName("\"fuse\"." + queryVO.getTbName());
        queryVO.setListByTypeStr("\"" + queryVO.getListByTypeStr() + "\"");
        List<String> list = dataSourceManageMapper.selectByTable(queryVO);
        ResVO resVO = new ResVO();
        return resVO;
    }

    public void updateOrSave(SaveVO saveVO) {
        List<String> fileName = new ArrayList<>();
        List<String> valueName = new ArrayList<>();
        Iterator<Map.Entry<String, String>> iterator = saveVO.getMap().entrySet().iterator();
        StringBuilder updateSql = new StringBuilder("update");
        updateSql.append("\"fuse\".");
        updateSql.append("\"");
        updateSql.append(saveVO.getTbName());
        updateSql.append("\" ");
        updateSql.append("set ");
        Double lon = 0d;
        Double lat = 0d;
        while (iterator.hasNext()) {
            Map.Entry<String, String> next = iterator.next();
            String key = next.getKey();
            if (key.equals("id")) {
                continue;
            }
            String value = next.getValue();
            fileName.add(key);
            valueName.add(value);
            updateSql.append("\"" + key + "\"=\'" + value + "\',");
            if ("lat".equals(key) && StringUtils.isNotBlank(value)) {
                lat = Double.valueOf(value);
            }
            if ("lon".equals(key) && StringUtils.isNotBlank(value)) {
                lon = Double.valueOf(value);
            }
        }
        if (lat > 0 && lon > 0) {
            updateSql.append("poi = ST_SetSRID(ST_Point(" + lon + "," + lat + "), 4326) where id='" + saveVO.getId() + "';");
        }
        // id 为空保存ST_
        if (StringUtils.isBlank(saveVO.getId())) {
            StringBuilder sql = new StringBuilder("insert into ");
            sql.append("\"fuse\".");
            sql.append("\"");
            sql.append(saveVO.getTbName());
            sql.append("\" ");
            sql.append(" (");
            sql.append("\"id\" ");
            for (String s : fileName) {
                sql.append(",");
                sql.append("\"");
                sql.append(s);
                sql.append("\" ");
            }
            sql.append(",");
            sql.append("\"poi\" ");
            sql.append(" )");
            sql.append("VALUES ");
            sql.append(" ('");
            sql.append(UUID.randomUUID().toString());
            sql.append("'");
            for (String value : valueName) {
                sql.append(",");
                sql.append("'");
                sql.append(value);
                sql.append("'");
            }
            sql.append(",");
            sql.append("'");
            sql.append("ST_SetSRID(ST_Point(" + lon + "," + lat + "), 4326)");
            sql.append("'");
            sql.append(" )");
            sql.append(";");
            dataSourceManageMapper.createable(sql.toString());
        } else {
            dataSourceManageMapper.createable(updateSql.toString());
        }

    }

    public Map<String, Object> selectList(QueryVO queryVO) {
        Map<String, Object> map = new HashMap<>();
        if (queryVO.getPageNo() > 1) {
            queryVO.setPageNo((queryVO.getPageNo() - 1) * queryVO.getPageSize());
        } else {
            queryVO.setPageNo(0);
        }
        queryVO.setTbName("\"fuse\"." + queryVO.getTbName());
        Integer integer = dataSourceManageMapper.selectByTableAndnameCount(queryVO);
        List<Map<String, String>> maps = dataSourceManageMapper.selectByTableAndname(queryVO);
        map.put("count", integer);
        map.put("dataList", maps);
        return map;
    }

    public Map<String, Object> setPoint(QueryVO queryVO) {
        Map<String, Object> map = new HashMap<>();
        queryVO.setTbName("\"fuse\"." + queryVO.getTbName());
        List<Map<String, String>> maps = dataSourceManageMapper.selectByTableAndname(queryVO);
        if (CollectionUtils.isNotEmpty(maps)) {
            for (Map<String, String> stringStringMap : maps) {
                String lat = stringStringMap.get("lat");
                String lon = stringStringMap.get("lon");
                String id = stringStringMap.get("id");
                String sql = "update " + "\"fuse\"." + queryVO.getTbName()
                        + " set \"poi\"=POINT(" + lon + "," + lat + ") where \"id\"=" + id + ";";
                dataSourceManageMapper.createable(sql);
            }
        }
        return map;
    }

    public void delete(SaveVO saveVO) {
        String tableName = "\"fuse\"." + saveVO.getTbName();
        StringBuilder sql = new StringBuilder("delete from");
        sql.append(tableName);
        sql.append(" where id='");
        sql.append(saveVO.getId());
        sql.append("'");
        sql.append(";");
        dataSourceManageMapper.createable(sql.toString());
    }


}
